package com.emm.yixun.marketing.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import com.emm.yixun.common.model.dto.*;
import com.emm.yixun.common.utils.MathUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.ProcessInstanceHistoryLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.druid.util.StringUtils;
import com.emm.yixun.basic.service.DataPermissionService;
import com.emm.yixun.basic.service.DictionaryService;
import com.emm.yixun.basic.service.NodeUserService;
import com.emm.yixun.basic.service.NoticeService;
import com.emm.yixun.basic.service.PayDepositService;
import com.emm.yixun.basic.service.PriceSchemeDetailService;
import com.emm.yixun.basic.service.PriceSchemeService;
import com.emm.yixun.basic.service.ProjectBuildingService;
import com.emm.yixun.basic.service.ProjectCarareaService;
import com.emm.yixun.basic.service.ProjectCarportService;
import com.emm.yixun.basic.service.ProjectPremisesService;
import com.emm.yixun.basic.service.ProjectRoomService;
import com.emm.yixun.basic.service.ProjectService;
import com.emm.yixun.basic.service.ProjectSettingService;
import com.emm.yixun.basic.service.ProjectUnitService;
import com.emm.yixun.basic.service.SubscribeService;
import com.emm.yixun.common.app.base.CommonResDTO;
import com.emm.yixun.common.constant.SysConstants;
import com.emm.yixun.common.exception.ResponseCode;
import com.emm.yixun.common.exception.XFUNExceptionCode;
import com.emm.yixun.common.model.Dictionary;
import com.emm.yixun.common.model.PayDeposit;
import com.emm.yixun.common.model.PriceScheme;
import com.emm.yixun.common.model.PriceSchemeDetail;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectBuilding;
import com.emm.yixun.common.model.ProjectCararea;
import com.emm.yixun.common.model.ProjectCarport;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.ProjectRoom;
import com.emm.yixun.common.model.ProjectSetting;
import com.emm.yixun.common.model.ProjectUnit;
import com.emm.yixun.common.model.Subscribe;
import com.emm.yixun.common.model.TreeNode;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.enums.CarportSalesStatusEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.LevelEnum;
import com.emm.yixun.common.model.enums.RoomStatusEnum;
import com.emm.yixun.common.model.enums.ValuationTypeEnum;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.common.utils.MsgUtil;
import com.emm.yixun.marketing.service.PriceSchemeServiceFacade;

@Service("priceSchemeServiceFacade")
@WebService(name = "com.emm.yixun.marketing.service.PriceSchemeServiceFacade")
public class PriceSchemeServiceFacadeImpl implements PriceSchemeServiceFacade {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private PriceSchemeService service;
	@Autowired
	private ProjectPremisesService premisesService;
	@Autowired
	private ProjectService projectService;

	@Autowired
	private ProjectBuildingService projectBuildingService;

	@Autowired
	private ProjectUnitService projectUnitService;

	@Autowired
	private ProjectRoomService projectRoomService;

	@Autowired
	private ProjectCarportService projectCarportService;

	@Autowired
	private ProjectCarareaService projectCarareaService;

	@Autowired
	private PriceSchemeDetailService priceSchemeDetailService;

	@Autowired
	private ProjectSettingService projectSettingService;

	@Autowired
	private PayDepositService payDepositService;

	@Autowired
	private SubscribeService subscribeService;
	@Autowired
	private NoticeService noticeService;
	@Autowired
	private DictionaryService dictionaryService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private DataPermissionService dataPermissionService;
	@Autowired
	private NodeUserService nodeUserService;
	@Autowired
	private PriceSchemeService priceSchemeService;

	@Override
	public Response<PriceSchemeDto> save(PriceSchemeDto dto, List<PriceSchemeView> list, User user) throws Exception {
		Response<PriceSchemeDto> response = new Response<PriceSchemeDto>();
		PriceSchemeDto schemedto = new PriceSchemeDto();
		if (null == dto) {
			response.setSuccess(false);
			response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("保存"));
			return response;
		} else {
			// 保存主表信息
			PriceSchemeDto entity = objectMount(dto, "1");
			entity.setStatus("00");
			entity.setMerchantId(user.getMerchantId());
			entity.setUserCode(user.getUserCode());
			entity.setCreateUserId(user.getId());
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
			entity.setDelFlag("0");
			schemedto = service.create(entity);
			// 保存子表数据
			for (PriceSchemeView info : list) {
				if (!dto.getValuationType().equals(ValuationTypeEnum.ValuationTypeEnum_4.getNo())) {
					if (info.getPrice() == null || info.getTotalPrice() == null) {
						continue;
					}
				} else {
					if (info.getTotalPrice() == null) {
						continue;
					}
				}
				PriceSchemeDetailDto infoObj = new PriceSchemeDetailDto();
				String str = info.getId();
				Long bid = new Long(str.subSequence(str.indexOf("_") + 1, str.length()).toString());
				String sub = str.subSequence(0, str.indexOf("_")).toString();
				if (sub.equals(LevelEnum.LevelEnum_5.getCode())) {
					infoObj.setRoomId(bid);
				} else {
					infoObj.setCarportId(bid);
				}
				infoObj.setPriceSchemeId(schemedto.getId());
				infoObj.setSetPrice(info.getInnerPrice());
				infoObj.setUnitPrice(info.getPrice());
				infoObj.setTotalPrice(info.getTotalPrice());
				infoObj.setDiscountRate(info.getDiscountRate());
				infoObj.setFloatingRange(info.getFloatingRange());
				infoObj.setMerchantId(user.getMerchantId());
				infoObj.setUserCode(user.getUserCode());
				infoObj.setCreateUserId(user.getId());
				infoObj.setCreateTime(new Date());
				infoObj.setUpdateTime(new Date());
				infoObj.setDelFlag("0");
				infoObj.setAccessCode(entity.getAccessCode());
				priceSchemeDetailService.create(infoObj);
			}
		}
		response.setSuccess(true);
		response.setEntity(schemedto);
		return response;
	}

	@Override
	public Response<Integer> updateByPrimaryKey(PriceSchemeDto dto, Boolean selective) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == selective || null == dto || null == dto.getId()) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("更新"));
				return response;
			}

			if (selective) {
				int count = service.update(dto);
				if (count > 0) {
					response.success(Integer.valueOf(count));
				} else {
					response.fail("90001", "更新数据失败");
				}
			} else {
				response.fail("90000", "暂未实现,修改参数selective=true即可");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("更新数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<Integer> deleteByPrimaryKey(Long id) {
		Response<Integer> response = new Response<Integer>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("删除"));
				return response;
			}
			PriceSchemeDto mDto = new PriceSchemeDto();
			mDto.setId(id);
			int count = service.destroy(mDto);
			if (count > 0) {
				// 删除明细
				PriceSchemeDetailDto detail = new PriceSchemeDetailDto();
				detail.setPriceSchemeId(id);
				priceSchemeDetailService.destroy(detail);
				response.success(Integer.valueOf(count));
			} else {
				response.fail("90001", "删除数据失败");
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("删除数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<PriceScheme> findById(Long id) {
		Response<PriceScheme> response = new Response<PriceScheme>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			PriceScheme entity = service.selectById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Response<PriceScheme> findWithOutDelById(Long id) {
		Response<PriceScheme> response = new Response<PriceScheme>();
		try {
			if (null == id) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("主键查询"));
				return response;
			}
			PriceScheme entity = service.selectWithOutDelFalgById(id);
			if (null == entity) {
				response.fail("90001", "主键查询数据失败");
			} else {
				response.success(entity);
				;
			}
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("主键查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<PriceScheme> findByDto(PriceSchemeDto dto) {
		ResponseList<PriceScheme> response = new ResponseList<PriceScheme>();
		try {
			if (null == dto) {
				response.fail(ResponseCode.PARAM_INVALID.getCode(), ResponseCode.PARAM_INVALID.formatMessage("查询"));
				return response;
			}
			List<PriceScheme> list = service.selectListByDto(dto);
			if (null == list) {
				response.fail(ResponseCode.NO_DATA_FOUND.getCode(), ResponseCode.NO_DATA_FOUND.formatMessage("查询"));
				return response;
			}
			response.success(list);
		} catch (Exception e) {
			response.fail(ResponseCode.SYSTEM_EXCEPTION.getCode(), ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询数据错误：{}", e);
		}
		return response;
	}

	@Override
	public Page<PriceScheme> findPageByDto(PriceSchemeDto dto, Integer begin, Integer row) {
		Page<PriceScheme> response = new Page<PriceScheme>();
		response.setPageSize(row);
		try {
			if (null == dto || null == begin || null == row) {
				response.setSuccess(false);
				response.setErrorMsg("参数不合法");
				return response;
			}

			PriceSchemeDto entity = objectMount(dto, "0");

			// 数据权限
			if (SysConstants.openDataPermission) {
				String dataPermission = dataPermissionService.dataPermissionCondition(entity.getPermissionUserId(),
						entity.getResourcesCode(), entity.getPrefix(), entity.getColumnName());
				String[] dataPermissionArr = dataPermission.split(":");
				if ("00".equals(dataPermissionArr[0])) {
					response.setErrorMsg(XFUNExceptionCode.USER_PRODUCTNOEXIST.getDesin());
					response.setSuccess(false);
					return response;
				}
				entity.setDataPermission(dataPermissionArr[1]);
			}

			Page<PriceScheme> page = service.getPageModel(entity, begin, row);
			if (null == page.getRows()) {
				response.setSuccess(false);
				response.setErrorMsg("分页数据不存在");
				return response;
			}
			response = page;
			response.setSuccess(true);
		} catch (Exception e) {
			response.setSuccess(false);
			response.setErrorMsg(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
			logger.error("查询分页数据错误：{}", e);
		}
		return response;
	}

	@Override
	public ResponseList<PriceSchemeView> findRoomList(String treeId, String bid) {
		ResponseList<PriceSchemeView> responseList = new ResponseList<PriceSchemeView>();
		try {
			List<PriceSchemeView> view = new ArrayList<>();
			if (StringUtils.isEmpty(bid)) {
				Map<String, String> map = getStrMap(treeId);
				String id = map.get("id");
				String prefix = map.get("prefix");
				// 查询项目下面所有的房间
				ProjectRoomDto roomDto = new ProjectRoomDto();
				roomDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				// 项目下的所有车位
				ProjectCarportDto carportDto = new ProjectCarportDto();
				carportDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
				switch (prefix) {
				case "PROJECT":
					// 查询条件
					roomDto.setProjectId(new Long(id));
					carportDto.setProjectId(new Long(id));
					break;
				case "PREMISES":
					// 组团下的房间
					roomDto.setPremisesId(new Long(id));
					// 组团下的车位
					carportDto.setPremisesId(new Long(id));
					break;
				case "BUILDING":
					roomDto.setBuildingId(new Long(id));
					// 楼栋下面没有车区(一个不存在的值)
					carportDto.setCarportCode("--");
					break;
				case "UNIT":
					roomDto.setUnitId(new Long(id));
					carportDto.setCarportCode("--");
					break;
				case "ROOM":
					roomDto.setId(new Long(id));
					carportDto.setCarportCode("--");
					break;
				case "CARAREA":
					// 不存在房间
					roomDto.setProjectCode("--");
					carportDto.setCarareaId(new Long(id));
					break;
				case "CARPORT":
					roomDto.setProjectCode("--");
					carportDto.setId(new Long(id));
					break;
				default:
					break;
				}
				view.addAll(findRoomList(roomDto));
				view.addAll(findPortCarList(carportDto));
			} else {
				// 根据业务ID查询
				PriceSchemeDetailDto detailDto = new PriceSchemeDetailDto();
				detailDto.setPriceSchemeId(new Long(bid));
				detailDto.setDelFlag("0");
				List<PriceSchemeDetail> detailList = priceSchemeDetailService.selectListWithOutDelFlagByDto(detailDto);
				for (PriceSchemeDetail list : detailList) {
					PriceSchemeView conves = new PriceSchemeView();
					String cid = null;
					if (list.getRoomId() != null) {
						ProjectRoom room = projectRoomService.selectById(list.getRoomId());
						cid = LevelEnum.LevelEnum_5.getCode() + "_" + list.getRoomId();
						conves.setComboxText(room.getCombinedName());
						conves.setBuildingArea(room.getBuildingArea());
						conves.setInnerArea(room.getInnerArea());
						conves.setInnerPrice(room.getInnerPrice());
					} else {
						cid = LevelEnum.LevelEnum_7.getCode() + "_" + list.getRoomId();
						conves.setComboxText(strByCarPort(list.getCarportId(), 0L));
					}
					conves.setPrice(list.getUnitPrice());
					conves.setTotalPrice(list.getTotalPrice());
					conves.setFloatingRange(list.getFloatingRange());
					conves.setDiscountRate(list.getDiscountRate());
					conves.setId(cid);
					view.add(conves);
				}
			}

			responseList.setEntity(view);
		} catch (Exception e) {
			responseList.setSuccess(false);
			responseList.setResultMessage(ResponseCode.SYSTEM_EXCEPTION.getMessageTemplate());
		}
		return responseList;
	}

	public Map<String, String> getStrMap(String str) {
		Map<String, String> map = new HashMap<String, String>();
		Long bid = new Long(str.subSequence(str.indexOf("_") + 1, str.length()).toString());
		String sub = str.subSequence(0, str.indexOf("_")).toString();
		map.put("id", bid.toString());
		map.put("prefix", sub);
		return map;
	}

	/**
	 * 方法描述 : 车位的完整名称 创建者：ThinkPad 项目名称： emm-marketing 类名：
	 * PriceSchemeServiceFacadeImpl.java 版本： v1.0 创建时间： 2016年6月24日 下午1:40:35
	 * 
	 * @param id
	 * @param level
	 * @return String
	 */
	@Override
	public String strByCarPort(Long id, Long level) {
		ProjectCararea cararea = new ProjectCararea();
		ProjectCarport carPort = null;
		if (level.compareTo(0L) == 0) {
			carPort = projectCarportService.selectById(id);
			cararea = projectCarareaService.selectById(carPort.getCarareaId());
		} else {
			cararea = projectCarareaService.selectById(id);
		}
		ProjectPremises premises = premisesService.selectById(cararea.getPremisesId());
		Project project = projectService.selectById(premises.getProjectId());
		String str = project.getProjectName() + "-->" + premises.getGroupName() + "-->" + cararea.getCarareaName();
		if (carPort != null) {
			str += "-->" + carPort.getCarportName();
		}
		return str;
	}

	/**
	 * 方法描述 : 房间集合 创建者：ThinkPad 项目名称： emm-marketing 类名：
	 * PriceSchemeServiceFacadeImpl.java 版本： v1.0 创建时间： 2016年6月24日 下午1:55:23
	 * 
	 * @param roomDto
	 * @return List<PriceSchemeView>
	 */
	public List<PriceSchemeView> findRoomList(ProjectRoomDto roomDto) {
		List<PriceSchemeView> view = new ArrayList<PriceSchemeView>();
		List<ProjectRoom> room = projectRoomService.selectListByDto(roomDto);
		if (room != null && room.size() > 0) {
			for (ProjectRoom roomObj : room) {
				PriceSchemeView conves = new PriceSchemeView();
				conves.setId(LevelEnum.LevelEnum_5.getCode() + "_" + roomObj.getId());
				conves.setComboxText(roomObj.getCombinedName());
				conves.setBuildingArea(roomObj.getBuildingArea());
				conves.setInnerArea(roomObj.getInnerArea());
				conves.setInnerPrice(roomObj.getInnerPrice());
				conves.setRoomStatus(roomObj.getRoomStatus());

				/**
				 * 获取房源的最新生效的价格方案中的价格
				 * 此处的价格,可能来自于不同的价格方案

				PriceSchemeDetail priceSchemeDetail = priceSchemeDetailService.selectEntityByRoomId(roomObj.getId());
				if (null != priceSchemeDetail) {
					conves.setPrice(priceSchemeDetail.getUnitPrice());
					conves.setTotalPrice(priceSchemeDetail.getTotalPrice());
					conves.setDiscountRate(priceSchemeDetail.getDiscountRate()==null?new BigDecimal("0"):priceSchemeDetail.getDiscountRate());
					conves.setFloatingRange(priceSchemeDetail.getFloatingRange());
				}
				 */

				view.add(conves);
			}
		}
		return view;
	}

	/**
	 * 方法描述 : 车位集合 创建者：ThinkPad 项目名称： emm-marketing 类名：
	 * PriceSchemeServiceFacadeImpl.java 版本： v1.0 创建时间： 2016年6月24日 下午1:58:05
	 * 
	 * @param carportDto
	 * @return List<PriceSchemeView>
	 */
	public List<PriceSchemeView> findPortCarList(ProjectCarportDto carportDto) {
		List<PriceSchemeView> view = new ArrayList<PriceSchemeView>();
		List<ProjectCarport> carportList = projectCarportService.selectListByDto(carportDto);
		if (carportList != null && carportList.size() > 0) {
			for (ProjectCarport carportObj : carportList) {
				PriceSchemeView conves = new PriceSchemeView();
				conves.setId("CARPORT_" + carportObj.getId());
				conves.setComboxText(strByCarPort(carportObj.getId(), 0L));
				view.add(conves);
			}
		}
		return view;
	}

	/**
	 * 方法描述 : 价格方案的挂载点 创建者：ThinkPad 项目名称： emm-marketing 类名：
	 * PriceSchemeServiceFacadeImpl.java 版本： v1.0 创建时间： 2016年6月25日 上午10:44:55
	 * 
	 * @param dto
	 * @return PriceSchemeDto
	 */
	public PriceSchemeDto objectMount(PriceSchemeDto dto, String type) {
		if (!StringUtils.isEmpty(dto.getTreeId())) {
			Map<String, String> map = getStrMap(dto.getTreeId());
			Long id = new Long(map.get("id"));
			Long projectId = null;
			String prefix = map.get("prefix");
			switch (prefix) {
			case "PROJECT":
				// 查询条件
				projectId = id;
				dto.setProjectId(id);
				break;
			case "PREMISES":
				ProjectPremises premises = premisesService.selectById(id);
				projectId = premises.getProjectId();
				dto.setProjectId(projectId);
				dto.setPremisesId(id);
				break;
			case "BUILDING":
				ProjectBuilding building = projectBuildingService.selectById(id);
				projectId = building.getProjectId();
				dto.setProjectId(projectId);
				dto.setPremisesId(building.getPremisesId());
				dto.setBuildingId(id);
				break;
			case "UNIT":
				ProjectUnit unit = projectUnitService.selectById(id);
				projectId = unit.getProjectId();
				dto.setProjectId(projectId);
				dto.setPremisesId(unit.getPremisesId());
				dto.setBuildingId(unit.getBuildingId());
				dto.setUnitId(id);
				break;
			case "ROOM":
				ProjectRoom room = projectRoomService.selectById(id);
				projectId = room.getProjectId();
				dto.setProjectId(projectId);
				dto.setBuildingId(room.getBuildingId());
				dto.setPremisesId(room.getPremisesId());
				dto.setUnitId(room.getUnitId());
				dto.setRoomId(id);
				break;
			case "CARAREA":
				ProjectCararea cararea = projectCarareaService.selectById(id);
				projectId = cararea.getProjectId();
				dto.setCarareaId(id);
				break;
			case "CARPORT":
				projectCarportService.selectById(id);
				ProjectCarport carPort = projectCarportService.selectById(id);
				projectId = carPort.getProjectId();
				dto.setCarportId(id);
				break;
			default:
				break;
			}
			if (type.equals("1")) {
				Project project = projectService.selectById(projectId);
				dto.setAccessCode(project.getProjectCode());
			}
		}
		return dto;
	}

	@Override
	public String findTreeIdByBesId(Long id) {
		PriceScheme entity = service.selectWithOutDelFalgById(id);
		if (entity.getRoomId() != null) {
			return LevelEnum.LevelEnum_5.getCode() + "_" + entity.getRoomId();
		} else if (entity.getUnitId() != null) {
			return LevelEnum.LevelEnum_4.getCode() + "_" + entity.getUnitId();
		} else if (entity.getBuildingId() != null) {
			return LevelEnum.LevelEnum_3.getCode() + "_" + entity.getBuildingId();
		} else if (entity.getPremisesId() != null) {
			return LevelEnum.LevelEnum_2.getCode() + "_" + entity.getPremisesId();
		} else if (entity.getProjectId() != null) {
			return LevelEnum.LevelEnum_1.getCode() + "_" + entity.getProjectId();
		}
		return null;
	}

	@Override
	public void taskRun(Long id) {
		PriceSchemeDto dto = new PriceSchemeDto();
		if (id == null) {
			dto.setStatus("01");
			dto.setExecutionDate(new Date());
		} else {
			dto.setId(id);
		}

		List<PriceScheme> priceScheme = service.selectListByDto(dto);
		if (priceScheme != null && priceScheme.size() > 0) {
			for (PriceScheme obj : priceScheme) {
				PriceSchemeDto entity = new PriceSchemeDto();
				entity.setId(obj.getId());
				entity.setStatus("10");
				entity.setEffectiveDate(new Date());
				service.update(entity);
				// 更改方案下面的明细，（车区或者/房间的状态为可售）
				PriceSchemeDetailDto detail = new PriceSchemeDetailDto();
				detail.setPriceSchemeId(obj.getId());
				detail.setDelFlag("0");
				List<PriceSchemeDetail> detailList = priceSchemeDetailService.selectListByDto(detail);
				if (null == detailList || detailList.size() == 0) {
					continue;
				}
				for (PriceSchemeDetail detailobj : detailList) {
					if (detailobj.getRoomId() != null) {
						// 只更改房间状态为初始状态的房间
						ProjectRoom queryRoom = projectRoomService.selectById(detailobj.getRoomId());
						if (queryRoom.getRoomStatus().equals(RoomStatusEnum.SALEL.getNo())) {
							ProjectRoomDto roomDto = new ProjectRoomDto();
							roomDto.setId(detailobj.getRoomId());
							roomDto.setRoomStatus(RoomStatusEnum.VENDIBILITY.getNo());
							projectRoomService.update(roomDto);
						}

					} else if (detailobj.getCarportId() != null) {
						ProjectCarportDto carPort = new ProjectCarportDto();
						carPort.setId(detailobj.getCarportId());
						carPort.setCarportSalesStatus(CarportSalesStatusEnum.VENDIBILITY.getNo());
						projectCarportService.update(carPort);
					}
				}
			}
		}
	}

	public List<TreeNode> findAreaByPremisesId(Long premisesId) {
		// 组团下的车区
		ProjectCarareaDto carportDto = new ProjectCarareaDto();
		carportDto.setPremisesId(premisesId);
		carportDto.setDelFlag("0");
		List<ProjectCararea> projectCarareaList = projectCarareaService.selectListByDto(carportDto);
		List<TreeNode> carportTreeList = new ArrayList<TreeNode>();
		if (projectCarareaList != null && projectCarareaList.size() > 0) {

			for (ProjectCararea carportObj : projectCarareaList) {

				TreeNode carareaNode = new TreeNode();
				carareaNode.setId("CARAREA_" + carportObj.getId());
				carareaNode.setText(carportObj.getCarareaName());
				// 车区下面的车位
				ProjectCarportDto carPortDto = new ProjectCarportDto();
				carPortDto.setCarareaId(carportObj.getId());
				carPortDto.setDelFlag("0");
				List<ProjectCarport> carPortList = projectCarportService.selectListByDto(carPortDto);
				if (carPortList != null && carPortList.size() > 0) {
					carareaNode.setLeaf(false);
					List<TreeNode> portTreeNode = new ArrayList<TreeNode>();
					for (ProjectCarport carPortObj : carPortList) {
						TreeNode carPortTree = new TreeNode();
						carPortTree.setId("CARPORT_" + carPortObj.getId());
						carPortTree.setText(carPortObj.getCarportName());
						carPortTree.setLeaf(true);
						portTreeNode.add(carPortTree);
					}
					carareaNode.setLeaf(false);
					carportTreeList.add(carareaNode);
					carareaNode.setChildren(portTreeNode);
				} else {
					carareaNode.setLeaf(true);
				}
			}
		}
		return carportTreeList;
	}

	@Override
	public Response<BigDecimal> findPriceByRoomId(Long roomId, Long payDepositId, Long subscribeId) {
		Response<BigDecimal> reqResponse = new Response<BigDecimal>();
		reqResponse.setSuccess(true);
		if (payDepositId != null) {
			PayDeposit payDeposit = payDepositService.selectById(payDepositId);
			reqResponse.setEntity(payDeposit.getFloatingRange());
		} else if (subscribeId != null) {
			Subscribe subscribe = subscribeService.selectById(subscribeId);
			reqResponse.setEntity(subscribe.getFloatingRange());
		} else {
			PriceSchemeDetail detail = priceSchemeDetailService.selectEntityByRoomId(roomId);
			reqResponse.setEntity(detail.getFloatingRange());
		}
		return reqResponse;
	}

	/**
	 * 创建消息
	 */
	@Override
	public CommonResDTO addNotice_JGFA(PriceSchemeDto priceSchemeDto, Map<String, Object> managerMap,
			String procInstId) {
		CommonResDTO resDto = new CommonResDTO();
		try {
			// 价格方案名称
			String schemeName = priceSchemeDto.getName();
			String projectCode = "";
			String projectName = "";
			if (null != priceSchemeDto.getProjectId()) {
				Project project = projectService.selectById(priceSchemeDto.getProjectId());
				if (null != project) {
					projectCode = project.getProjectCode();
					projectName = project.getProjectName();
				} else {
					logger.info("价格方案审批消息失败,房源不存在! 方案Id = " + priceSchemeDto.getId());
					resDto.setErrorCode("00000");
					resDto.setErrorMsg("价格方案审批消息失败,房源不存在!");
					resDto.setResult("0");
					return resDto;
				}
			}

			/**
			 * 消息接收人 1、根据审批节点人员确定
			 */
			// 获取当前项目下审批节点人map
			ProjectSettingDto pDto = new ProjectSettingDto();
			pDto.setProjectCode(projectCode);
			ProjectSetting pObj = projectSettingService.selectByDto(pDto);
			Map<String, Object> variables = new HashMap<String, Object>();
			variables.put("projectApprovalUser", pObj.getProjectLeader());
			variables.put("marketingApprovalUser", pObj.getSaleLeader());
			variables.put("caseApprovalUser", pObj.getFieldLeader());
			variables.put("financeApprovalUser", pObj.getFinanceLeader());
			variables.put("saleManagerApprovalUser", pObj.getMaLeader());

			// 获取审批人userId
			List<User> userList = new ArrayList<User>();
			ProcessInstanceHistoryLog processInstanceHistoryLog = historyService
					.createProcessInstanceHistoryLogQuery(procInstId).singleResult();
			userList = nodeUserService.selectProcUserList(priceSchemeDto.getMerchantId(), null,
					processInstanceHistoryLog.getProcessDefinitionId(), null);
			if (userList.size() == 0) {
				logger.info("价格方案审批消息失败,待发送客户不存在! 面积补差Id = " + priceSchemeDto.getId());
				resDto.setErrorCode("00000");
				resDto.setErrorMsg("价格方案审批消息失败,待发送客户不存在!");
				resDto.setResult("0");
				return resDto;
			}

			// 无房认筹, 获取字典表dictionary_value = 'NT18' 的消息模板
			// 消息模板: 价格方案审批申请、方案名称：${schemeName}
			String msgTemp = "价格方案审批申请。方案名称：${schemeName}";
			String sendMsg = "";
			DictionaryDto dicDto = new DictionaryDto();
			dicDto.setDictionaryValue("NT18");
			Dictionary dic = dictionaryService.selectByDto(dicDto);
			if (dic != null) {
				msgTemp = dic.getDictionaryName();
			}
			sendMsg = msgTemp.replace("${schemeName}", schemeName);
			// 创建提醒消息及消息发送人信息
			Map<String, String> noticeParamMap = new HashMap<String, String>();
			noticeParamMap.put("noticeDicId", "181");
			noticeParamMap.put("noticeTempType", "NT18");
			noticeParamMap.put("sendMsg", sendMsg);
			noticeParamMap.put("title", "价格方案审批申请");
			noticeParamMap.put("merchantId", String.valueOf(priceSchemeDto.getMerchantId()));
			noticeParamMap.put("projectCode", projectCode);
			noticeParamMap.put("userCode", priceSchemeDto.getUserCode());
			noticeParamMap.put("accessCode", priceSchemeDto.getAccessCode());
			noticeParamMap.put("createUserId", String.valueOf(priceSchemeDto.getCreateUserId()));
			/*
			 * (ym) 提醒内容增加超链接 start
			 */
			Map<String, String> replaceValuesMap = new HashMap<String, String>();
			replaceValuesMap.put(MsgUtil.ROOM_ID, "");
			replaceValuesMap.put(MsgUtil.ROOM_NAME, "");
			replaceValuesMap.put(MsgUtil.CUSTOMER_ID, "");
			replaceValuesMap.put(MsgUtil.CUSTOMER_NAME, "");
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_ID, String.valueOf(priceSchemeDto.getId()));
			replaceValuesMap.put(MsgUtil.PRICE_SCHEME_NAME, schemeName);
			noticeParamMap.put("replaceValues", MsgUtil.getReplaceValues(replaceValuesMap));
			/*
			 * (ym) 提醒内容增加超链接 end
			 */
			NoticeDto noticeDto = noticeService.createNotice(noticeParamMap, userList, null);

			// 推送消息待处理......
			resDto = noticeService.pushMsg(projectCode, projectName, noticeDto, "价格方案审批申请");
		} catch (Exception e) {
			e.printStackTrace();
			resDto.setErrorCode("00000");
			resDto.setErrorMsg("价格方案审批申请,消息发送失败");
			resDto.setResult("0");
			return resDto;
		}
		return resDto;
	}

}
